import request from '@/utils/request'

const state = {
  // 可用积分
  availablePoints: 0,
  // 今日获得积分
  todayEarned: 0,
  // 广告观看次数
  adWatchCount: 0,
  // 积分交易记录
  transactions: [],
  // 积分统计
  stats: {}
}

const mutations = {
  SET_AVAILABLE_POINTS(state, points) {
    state.availablePoints = points || 0
  },
  
  SET_TODAY_EARNED(state, earned) {
    state.todayEarned = earned || 0
  },
  
  SET_AD_WATCH_COUNT(state, count) {
    state.adWatchCount = count || 0
  },
  
  SET_TRANSACTIONS(state, transactions) {
    state.transactions = transactions || []
  },
  
  SET_STATS(state, stats) {
    state.stats = stats || {}
  },
  
  // 增加积分
  ADD_POINTS(state, amount) {
    state.availablePoints += amount
  },
  
  // 减少积分
  SUBTRACT_POINTS(state, amount) {
    state.availablePoints = Math.max(0, state.availablePoints - amount)
  }
}

const actions = {
  // 获取积分余额
  async fetchBalance({ commit }) {
    try {
      console.log('正在获取积分余额...')
      const response = await request.get('/api/points/balance')
      console.log('积分余额响应:', response)
      
      if (response.success) {
        commit('SET_AVAILABLE_POINTS', response.data.points)
        console.log('积分余额设置完成:', response.data.points)
        return response.data
      } else {
        throw new Error(response.message || '获取积分余额失败')
      }
    } catch (error) {
      console.error('获取积分余额失败:', error)
      uni.showToast({
        title: error.message || '获取积分余额失败',
        icon: 'none'
      })
      throw error
    }
  },
  
  // 获取积分统计
  async fetchStats({ commit }) {
    try {
      console.log('正在获取积分统计...')
      const response = await request.get('/api/points/stats')
      console.log('积分统计响应:', response)
      
      if (response.success) {
        commit('SET_STATS', response.data)
        // 设置今日获得积分和观看次数
        commit('SET_TODAY_EARNED', response.data.todayEarned || 0)
        commit('SET_AD_WATCH_COUNT', response.data.adWatchCount || 0)
        console.log('积分统计设置完成:', response.data)
        return response.data
      } else {
        throw new Error(response.message || '获取积分统计失败')
      }
    } catch (error) {
      console.error('获取积分统计失败:', error)
      throw error
    }
  },
  
  // 获取积分交易记录
  async fetchTransactions({ commit }, params = {}) {
    try {
      const response = await request.get('/api/points/transactions', params)
      
      if (response.success) {
        commit('SET_TRANSACTIONS', response.data.transactions || response.data)
        return response.data
      } else {
        throw new Error(response.message || '获取积分记录失败')
      }
    } catch (error) {
      console.error('获取积分记录失败:', error)
      throw error
    }
  },
  
  // 每日签到
  async dailyCheckin({ commit, dispatch }) {
    try {
      const response = await request.post('/api/points/checkin')
      
      if (response.success) {
        // 更新积分余额
        commit('SET_AVAILABLE_POINTS', response.data.newBalance)
        
        uni.showToast({
          title: `签到成功，获得${response.data.rewardPoints}积分`,
          icon: 'success'
        })
        
        return response.data
      } else {
        throw new Error(response.message || '签到失败')
      }
    } catch (error) {
      console.error('签到失败:', error)
      uni.showToast({
        title: error.message || '签到失败',
        icon: 'none'
      })
      throw error
    }
  },
  
  // 观看广告获得积分
  async watchAdReward({ commit, dispatch }) {
    try {
      const response = await request.post('/api/points/watch-ad')
      
      if (response.success) {
        // 更新积分余额
        commit('SET_AVAILABLE_POINTS', response.data.newBalance)
        // 更新观看次数
        commit('SET_AD_WATCH_COUNT', response.data.todayWatchCount)
        
        uni.showToast({
          title: `观看完成，获得${response.data.rewardPoints}积分`,
          icon: 'success'
        })
        
        return response.data
      } else {
        throw new Error(response.message || '观看广告失败')
      }
    } catch (error) {
      console.error('观看广告奖励失败:', error)
      uni.showToast({
        title: error.message || '观看广告失败',
        icon: 'none'
      })
      throw error
    }
  }
}

const getters = {
  // 可用积分
  availablePoints: state => state.availablePoints,
  
  // 今日获得积分
  todayEarned: state => state.todayEarned,
  
  // 广告观看次数
  adWatchCount: state => state.adWatchCount,
  
  // 是否可以观看广告（每日限制20次）
  canWatchAd: state => state.adWatchCount < 20,
  
  // 积分交易记录
  transactions: state => state.transactions,
  
  // 积分统计
  stats: state => state.stats
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}